import Tkinter
import Feeds
import _viewsetup

class Reader():
	feeds = []

	def __init__(self, initialFeeds):
		Reader.feeds = initialFeeds

		self.window = Tkinter.Tk()
		for i in range(34):
                        Tkinter.Frame(self.window,height=10,width=10).grid(row=0,column=i)
                for i in range(56):
                        Tkinter.Frame(self.window,height=10,width=10).grid(row=i,column=0)

                self.buttons = {}
		self.views = {}
                self.ribbons = {}
                self.screens = {}

		_viewsetup.viewSetup(self)
		self.setScreen('mainmenu')

	def setScreen(self, viewname):
		self.clearScreen()

		self.screens[viewname].grid(row=0,column=0,padx=5,pady=5,rowspan=57,columnspan=34)

	def clearScreen(self):
		for x in self.screens.values():
                        x.grid_remove()

        def quickFeeds(self):
                self.screens['related'].grid_remove()
                
                self.ribbons['quickFeeds'].grid(row=1,column=13)
                self.views['article'].grid(row=10,column=3)

        def relatedFeeds(self):
                self.ribbons['quickFeeds'].frame.grid_remove()

                self.ribbons['related'].build()
                self.screens['related'].grid(row=29,column=0,rowspan=24,columnspan=33)
                self.views['article'].grid(row=10,column=3)

        def askForFeed(self,manageWindow):
                t = Tkinter.Toplevel()
                e = Tkinter.Entry(t,
                                  width=50,
                                  text='new URL:')
                e.pack()
                Tkinter.Button(t,
                               text='Add Feed',
                               command = lambda : self.addFeed(manageWindow,t,e))\
                               .pack()

        def addFeed(self,manageWindow,window,newURL):
                self.checkURL(newURL)
                Reader.feeds += [Feeds.URLfeed(newURL.get())]
                Feeds.create(Reader.feeds)
                for x in self.ribbons.values():
                        x.build()
                manageWindow.destroy()
                window.destroy()

        def checkURL(self,URL):
                print 'For now everything goes. If you catch my drift.'
                print
                print URL.get()
                print 'LOADING ...'

class View():

	def __init__(self,reader,screen,size = 6, articles = None):
		self.master = reader
		self.frame = Tkinter.Frame(screen)
		self.size = size
		self.row = 0
		self.column = 0
		
		if articles == None:
			self.articles = Reader.feeds[0].articles
		else:
			self.articles = articles
		self.topArticle = 0
		self.buttons = []

		F = Tkinter.Frame(self.frame,height=10,width=280)
                F.pack_propagate(0)
		Tkinter.Button(F,
                               text='/\\',
                               font=('Times',6),
                               command=lambda: self.moveArticles(-1))\
                               .pack(fill='both',expand=1)
                F.grid(row=0,column=0,rowspan=1,columnspan=28)
		F = Tkinter.Frame(self.frame,height=10,width=280)
                F.pack_propagate(0)
                Tkinter.Button(F,
                               text='\\/',
                               font=('Times',6),
                               command=lambda: self.moveArticles(1))\
                               .pack(fill='both',expand=1)
                F.grid(row=1+(self.size*5),column=0,rowspan=1,columnspan=28)

                Tkinter.Frame(self.frame,height=10,width=280).grid(row=2+(self.size*5),column=0,rowspan=1,columnspan=28)

		F = Tkinter.Frame(self.frame,height=10,width=280)
                F.pack_propagate(0)
                self.feedLabel = Tkinter.Label(F,
					       font = ('Times',6))
		self.feedLabel.pack(fill='both',expand=1)
                F.grid(row=3+(self.size*5),column=0,rowspan=1,columnspan=28)

		self.build()
		
	def build(self):
		for x in self.buttons:
			x.destroy()
		self.buttons = []

		for i in range(self.size):
                        F = Tkinter.Frame(self.frame,height=50,width=280)
                        F.pack_propagate(0)
                        if i < len(self.articles):
                                self.buttons += [Tkinter.Button(F,
                                                                text=str(self.articles[i+self.topArticle].headline),
        							wraplength = 260,
        							font = ('Times',8,'bold'),
                                                                command=lambda j = i: self.showArticle(self.articles[j+self.topArticle]))]
                        else:
                                self.buttons += [Tkinter.Button(F,state='disabled',bg='#666')]
                        self.buttons[-1].pack(fill='both',expand=1)
                        F.grid(row=1+(i*5),column=0,rowspan=5,columnspan=28)

	def moveArticles(self,delta):
		self.topArticle += delta
		if (self.topArticle < 0):
			self.topArticle += -delta
		elif (self.topArticle > (len(self.articles)-self.size)):
			self.topArticle += -delta
		else:
			self.build()

	def showArticle(self,newArticle):
		self.master.rHeadline.__setitem__('text',newArticle.headline)
		self.master.rText.__setitem__('state','normal')
		self.master.rText.delete('1.0','end')
		self.master.rText.insert('1.0',newArticle.getText())
		self.master.rText.__setitem__('state','disabled')
		
                self.master.ribbons['related'].feeds = []
		for x in Reader.feeds:
                        related =  []
                        for y in x.articles:
                                if y.compareTags(newArticle) > 0.0:
                                        related += [y]
                        
                        self.master.ribbons['related'].feeds += [x.copy()]
                        self.master.ribbons['related'].feeds[-1].articles = x.getArticlesByFilter(related)

		self.master.setScreen('article')

	def grid(self,row=None,column=None):
                if row == None:
                        row = self.row
                if column == None:
                        column = self.column
                self.frame.grid(row=row,column=column,rowspan=4+5*self.size,columnspan=28)

class Ribbon():

        def __init__(self, parent, view, size=5, feeds=None, label='SOURCE'):
                self.frame = Tkinter.Frame(parent)
                self.view = view
                self.buttons = []
                self.curFeed = 0
                if size%2 == 0:
                        size += 1
                self.size = (size - 1)/2

		self.feeds = []
		if feeds == None:
                        feeds = Reader.feeds
		for x in feeds:
                        self.feeds += [x]

		self.label = label
		self.view.feedLabel.__setitem__('text',self.label + ': ' + self.feeds[0].sourceName)

                F = Tkinter.Frame(self.frame,height=80,width=10)
                F.pack_propagate(0)
                Tkinter.Button(F,
                               text='<',
                               command=lambda: self.changeCurFeed(-1))\
                               .pack(fill='both',expand=1)
                F.grid(row=0,column=0,rowspan=8,columnspan=1)
                F = Tkinter.Frame(self.frame,height=80,width=10)
                F.pack_propagate(0)
                Tkinter.Button(F,
                               text='>',
                               command=lambda: self.changeCurFeed(1))\
                               .pack(fill='both',expand=1)
                F.grid(row=0,column=2 + (6 * ((2 * self.size) + 1)),rowspan=8,columnspan=1)

                self.build()

        def build(self):
                for x in self.buttons:
                        x.destroy()
                self.buttons = []
                count = 0
                for i in range((-self.size + self.curFeed),(self.size + 1 + self.curFeed)):
                        F = Tkinter.Frame(self.frame,height=80,width=60)
                        F.pack_propagate(0)
                        self.buttons += [Tkinter.Button(F,
                                                        text=self.feeds[i%len(self.feeds)].sourceName,
							wraplength = 35,
							font = ('Times',6),
                                                        command=lambda j=count: self.changeCurFeed(j-self.size))]
                        if ((count < self.size) and (count < ((self.size*2) + 1) - len(self.feeds)))\
                           or ((count>self.size) and (len(self.feeds)-1) < (count - self.size)):
                                self.buttons[-1].__setitem__('state','disabled')
                                self.buttons[-1].__setitem__('font',('Times',4))
                                self.buttons[-1].__setitem__('bg','#666')
                        self.buttons[-1].pack(fill='both',expand=1)
                        F.grid(row=0,column=2 + (count * 6),rowspan=8,columnspan=6)
                        count += 1
                self.view.feedLabel.__setitem__('text',self.label + ': ' + self.feeds[self.curFeed].sourceName)

        def changeCurFeed(self,delta):
                self.curFeed = (self.curFeed + delta) % len(self.feeds)
                self.build()

                self.view.articles = self.feeds[self.curFeed].articles
                self.view.topArticle = 0
		self.view.build()

	def grid(self,row=None,column=None):
                self.changeCurFeed(0)
                if row == None:
                        row = self.row
                if column == None:
                        column = self.column
                self.frame.grid(row=row,column=column,rowspan=8,columnspan=8+12*self.size)
